#!/usr/bin/env node

/**
 * 娱乐城开奖广播格式测试脚本（仅格式测试，不依赖Redis）
 * 测试大小开奖(act_id: 1337)和赤壁开奖(act_id: 260)的广播格式区别
 */

// 模拟开奖结果数据
const mockDiceResult = {
    num1: 1,
    num2: 2,
    num3: 3,
    sum: 6,
    isBig: false,
    isSmall: true,
    isOdd: false,
    isEven: true,
    isTriple: false,
};

// 模拟下注数据
const mockDiceBets = [
    { betAmount: 100, currencyType: 1 }, // 100金币
    { betAmount: 50, currencyType: 2 },  // 50银币
    { betAmount: 200, currencyType: 1 }, // 200金币
    { betAmount: 75, currencyType: 2 },  // 75银币
];

const mockChibiResult = {
    winningSide: 1,
    sideStats: { 1: 334660, 2: 150000, 3: 200000 },
    battleReport: "魏军大获全胜，敌军溃不成军",
    reportStr: "魏军大获全胜，敌军溃不成军",
};

// 模拟赤壁下注数据
const mockChibiBets = [
    { side: 1, betGold: 200000, betSilver: 0 },   // 魏国 200000金币
    { side: 1, betGold: 134660, betSilver: 0 },   // 魏国 134660金币
    { side: 2, betGold: 150000, betSilver: 0 },   // 蜀国 150000金币
    { side: 3, betGold: 200000, betSilver: 0 },   // 吴国 200000金币
];

/**
 * 测试大小开奖广播格式
 */
function testDiceBroadcast() {
    console.log('\n🎲 测试大小开奖广播格式 (act_id: 1337)');
    console.log('='.repeat(50));

    // 计算总下注金额（金币和银币分别计算）
    const totalBetGold = mockDiceBets.reduce((sum, bet) => {
        return sum + (bet.currencyType === 1 ? bet.betAmount : 0);
    }, 0);

    const totalBetSilver = mockDiceBets.reduce((sum, bet) => {
        return sum + (bet.currencyType === 2 ? bet.betAmount : 0);
    }, 0);

    // 生成开奖结果描述
    const { num1, num2, num3, sum, isBig, isSmall, isOdd, isEven, isTriple } = mockDiceResult;

    // 构建开奖结果描述，使用标准格式
    let resultDescription = "";
    if (isTriple) {
        resultDescription = `三国鸭胜负已分,三豹子出现,所有下注三豹子的玩家获得10倍奖励`;
    } else if (isBig) {
        resultDescription = `三国鸭胜负已分,大点数出现,所有下注大点的玩家获得2倍奖励`;
    } else if (isSmall) {
        resultDescription = `三国鸭胜负已分,小点数出现,所有下注小点的玩家获得2倍奖励`;
    } else if (isOdd) {
        resultDescription = `三国鸭胜负已分,奇数点数出现,所有下注奇数的玩家获得2倍奖励`;
    } else if (isEven) {
        resultDescription = `三国鸭胜负已分,偶数点数出现,所有下注偶数的玩家获得2倍奖励`;
    } else {
        resultDescription = `三国鸭胜负已分,点数${sum}出现,所有下注点数${sum}的玩家获得2倍奖励`;
    }

    // 构建广播消息
    const diceBroadcastMessage = {
        act_id: 1337, // 大小开奖专用指令ID
        code: 0,
        data: {
            c: resultDescription,
            h: new Date().toLocaleTimeString("zh-CN", {
                hour: "2-digit",
                minute: "2-digit",
            }),
            id: Date.now(),
            n: "系统",
            rid: 1000,
            t: 6,
        },
    };

    console.log('📊 开奖结果数据:');
    console.log(`   骰子点数: ${num1}, ${num2}, ${num3}`);
    console.log(`   总点数: ${sum}`);
    console.log(`   是否大点: ${isBig}`);
    console.log(`   是否小点: ${isSmall}`);
    console.log(`   是否奇数: ${isOdd}`);
    console.log(`   是否偶数: ${isEven}`);
    console.log(`   是否三豹子: ${isTriple}`);

    console.log('\n💰 下注统计:');
    console.log(`   总下注金币: ${totalBetGold}`);
    console.log(`   总下注银币: ${totalBetSilver}`);

    console.log('\n📡 广播消息格式:');
    console.log(JSON.stringify(diceBroadcastMessage, null, 2));

    console.log('\n🔍 关键字段说明:');
    console.log(`   act_id: ${diceBroadcastMessage.act_id} (大小开奖专用)`);
    console.log(`   广播频道: casino.dice.result`);
    console.log(`   开奖描述: ${resultDescription}`);

    return diceBroadcastMessage;
}

/**
 * 测试赤壁开奖广播格式
 */
function testChibiBroadcast() {
    console.log('\n⚔️ 测试赤壁开奖广播格式 (act_id: 260)');
    console.log('='.repeat(50));

    // 计算总下注金额（金币和银币分别计算）
    const totalBetGold = mockChibiBets.reduce((sum, bet) => {
        return sum + (bet.betGold || 0);
    }, 0);

    const totalBetSilver = mockChibiBets.reduce((sum, bet) => {
        return sum + (bet.betSilver || 0);
    }, 0);

    // 计算获胜方总下注金额
    const { winningSide } = mockChibiResult;
    const winningBets = mockChibiBets.filter((bet) => bet.side === winningSide);
    const winningBetGold = winningBets.reduce((sum, bet) => {
        return sum + (bet.betGold || 0);
    }, 0);

    const winningBetSilver = winningBets.reduce((sum, bet) => {
        return sum + (bet.betSilver || 0);
    }, 0);

    // 生成开奖结果描述
    const sideNames = { 1: "魏国", 2: "蜀国", 3: "吴国" };
    const winningSideName = sideNames[winningSide] || "未知";

    // 构建开奖结果描述，使用标准格式
    let resultDescription = "";
    if (winningBetGold > 0 && winningBetSilver > 0) {
        resultDescription = `三国鸭胜负已分,获胜国给支持者发放战利品${winningBetGold}金${winningBetSilver}银`;
    } else if (winningBetGold > 0) {
        resultDescription = `三国鸭胜负已分,获胜国给支持者发放战利品${winningBetGold}金0银`;
    } else if (winningBetSilver > 0) {
        resultDescription = `三国鸭胜负已分,获胜国给支持者发放战利品0金${winningBetSilver}银`;
    } else {
        resultDescription = `三国鸭胜负已分,获胜国给支持者发放战利品0金0银`;
    }

    // 构建广播消息
    const chibiBroadcastMessage = {
        act_id: 260, // 赤壁开奖专用指令ID
        code: 0,
        data: {
            c: resultDescription,
            h: new Date().toLocaleTimeString("zh-CN", {
                hour: "2-digit",
                minute: "2-digit",
            }),
            id: Date.now(),
            n: "系统",
            rid: 1000,
            t: 6,
        },
    };

    console.log('📊 开奖结果数据:');
    console.log(`   获胜国家: ${winningSideName} (ID: ${winningSide})`);
    console.log(`   魏国下注: ${mockChibiBets.filter(b => b.side === 1).reduce((sum, b) => sum + (b.betGold || 0), 0)} 金币`);
    console.log(`   蜀国下注: ${mockChibiBets.filter(b => b.side === 2).reduce((sum, b) => sum + (b.betGold || 0), 0)} 金币`);
    console.log(`   吴国下注: ${mockChibiBets.filter(b => b.side === 3).reduce((sum, b) => sum + (b.betGold || 0), 0)} 金币`);

    console.log('\n💰 下注统计:');
    console.log(`   获胜方下注金币: ${winningBetGold}`);
    console.log(`   获胜方下注银币: ${winningBetSilver}`);
    console.log(`   本期总下注金币: ${totalBetGold}`);
    console.log(`   本期总下注银币: ${totalBetSilver}`);

    console.log('\n📡 广播消息格式:');
    console.log(JSON.stringify(chibiBroadcastMessage, null, 2));

    console.log('\n🔍 关键字段说明:');
    console.log(`   act_id: ${chibiBroadcastMessage.act_id} (赤壁开奖专用)`);
    console.log(`   广播频道: casino.chibi.result`);
    console.log(`   开奖描述: ${resultDescription}`);

    return chibiBroadcastMessage;
}

/**
 * 主函数
 */
function main() {
    console.log('🎮 娱乐城开奖广播格式测试（标准格式验证）');
    console.log('='.repeat(50));
    console.log('本测试将验证大小开奖和赤壁开奖的广播格式区别');
    console.log('按照标准格式：所有开奖都使用"三国鸭胜负已分"作为开头');
    console.log('');

    try {
        // 测试广播格式
        testDiceBroadcast();
        testChibiBroadcast();

        console.log('\n📋 广播格式对比总结:');
        console.log('   🎲 大小开奖: act_id: 1337, 频道: casino.dice.result');
        console.log('   ⚔️ 赤壁开奖: act_id: 260, 频道: casino.chibi.result');
        console.log('   📝 两种广播使用不同的指令ID，便于客户端区分处理');
        console.log('   🎯 所有开奖广播都使用"三国鸭胜负已分"作为开头，保持格式统一');
        console.log('   💰 赤壁开奖显示获胜国奖励，即使某种货币为0也会显示"0金"或"0银"');

        console.log('\n🎉 格式测试完成！');
        console.log('\n📚 相关文档:');
        console.log('   - CASINO_BROADCAST_FORMATS_README.md - 广播格式说明');
        console.log('   - 娱乐城WebSocket接口映射表.md - 接口映射关系');

    } catch (error) {
        console.error('❌ 测试过程中发生错误:', error.message);
    }
}

// 运行测试
if (require.main === module) {
    main();
}

module.exports = {
    testDiceBroadcast,
    testChibiBroadcast,
}; 